{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "\n",
    "# 独立使用django model（一）\n",
    "# Django Shell\n",
    "# 项目根目录中打开Django Shell : python manage.py shell\n",
    "# import django\n",
    "# django.setup()  # 装载Django\n",
    "# 调用model\n",
    "# django 快速入门 数据操作 https://blog.csdn.net/u011054333/article/details/78767724\n",
    "\n",
    "# 独立使用django model（二）\n",
    "import sys\n",
    "import os\n",
    "import json\n",
    "import requests\n",
    "from django.core.files import File\n",
    "from django.core.files.base import ContentFile\n",
    "\n",
    "\n",
    "# 建立外部脚本链接django项目\n",
    "# 添加环境变量\n",
    "'''\n",
    "print(os.path.abspath('__file__'))\n",
    "print(os.path.dirname(os.path.abspath('__file__')))\n",
    "print(os.path.dirname(os.path.dirname(os.path.abspath('__file__'))))\n",
    "/Users/zhaojinhui/Desktop/webapp/backend/rmis/jupyter_notebook/__file__\n",
    "/Users/zhaojinhui/Desktop/webapp/backend/rmis/jupyter_notebook\n",
    "/Users/zhaojinhui/Desktop/webapp/backend/rmis\n",
    "'''\n",
    "project = os.path.dirname(os.getcwd())  # get current work directory\n",
    "sys.path.append(project)\n",
    "sys.path.append(os.path.join(project,'rmis'))\n",
    "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')\n",
    "# sys.path.append已设置临时环境变量，可以找到rmis.settings，脚本是外部脚本，只是放在了项目当中而已\n",
    "# 相关数据库配置等在settings.py文件中\n",
    "\n",
    "# 导入并装载django\n",
    "import django\n",
    "django.setup()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from good.models import Good, GoodMultimedia\n",
    "media = GoodMultimedia()\n",
    "media.fk_good = Good.objects.get(id=86)\n",
    "media.type = '00'\n",
    "with open('/Users/zhaojinhui/Documents/图片/三只兔子.jpeg','rb') as img:\n",
    "    media.uri.save('test_local_picture_save.jpeg', ContentFile(img.read()))\n",
    "media.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "media = GoodMultimedia()\n",
    "media.fk_good = Good.objects.get(id=86)\n",
    "media.type = '00'\n",
    "response = requests.get('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png')\n",
    "media.uri.save('test_online_picture_save.jpeg', ContentFile(response.content))\n",
    "media.save()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
